package com.rc.evcharger.task;

import com.rc.evcharger.common.base.BaseTask;
import com.rc.evcharger.common.utils.DataUtil;
import com.rc.evcharger.common.utils.TimeoutUtil;
import com.rc.evcharger.service.CommandService;
import io.netty.util.Timeout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 发送有关充电/停止充电指令，一定时间内没有收到回复确认帧就执行该定时器去读取枪的状态
 * @author Administrator
 */
@Component
public class OverTimeTask extends SupperTask implements BaseTask {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    Map<String, Long> OMIds = null;

    @Autowired
    private CommandService commandService;

    @Override
    public void removeTask(String rtua) {
        TimeoutUtil timeoutUtil = TimeoutUtil.newInstance();
        Timeout timeout = timeoutUtil.getTimeout(this.getClass().getName() + rtua);
        logger.warn("OverTimeTask移除定时器：" + this.getClass().getName() + rtua);
        if (timeout != null) {
            timeout.cancel();
            timeoutUtil.removeTimeout(rtua);
        }
    }

    @Override
    public void runTask(Timeout timeout) throws Exception {
        TimeoutUtil timeoutUtil = TimeoutUtil.newInstance();
        String key = timeoutUtil.getRtua(timeout);
        String rtuaGun = key.replace(this.getClass().getName(), "");
        String rtua = rtuaGun.substring(0, 11);
        String gunNum = rtuaGun.substring(12, 14).trim();

        String[] codes = {DataUtil.dataCodes[19][0].toString(), DataUtil.dataCodes[14][0].toString()};
        try {
//            for (int i = 0; i < 3; i++) {
//                commandService.sendCurrDataCode(null, rtua, gunNum, codes);
//                Thread.sleep(1000 * 17);
//            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // }
        timeoutUtil.removeTimeout(rtuaGun);
        timeout.cancel();

    }

    @Override
    public void addTask(String rtua, String gunNum, Integer time, TimeUnit tu) {
        TimeUnit timeUnit = TimeUnit.MINUTES;
        if (tu != null) {
            timeUnit = tu;
        }
        if (time == null) {
            time = this.MINUTE;
        }

        TimeoutUtil timeoutUtil = TimeoutUtil.newInstance();
        Timeout timeout = timer.newTimeout(this, time, timeUnit);
        String rtuaGun = DataUtil.getKey(rtua, gunNum);
        logger.warn("OverTimeTask添加定时：" + rtuaGun);
        timeoutUtil.addTimeout(this.getClass().getName() + rtuaGun, timeout); // }
    }
}
